<!DOCTYPE html>
<html lang="zh-cn">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>监听数组</title>
  </head>
  <body>
    <script>
     

      // 监听数组的准备工作
      let arrProto = Array.prototype;
      let newObj = Object.create(arrProto);
      let watchMethods = ["push", "pop", "shift", "unshift", "splice"];
      watchMethods.forEach((method) => {
        newObj[method] = function () {
          render();
          arrProto[method].call(this, ...arguments);
        };
      });

      // 开始监听
      let data = {
        a: 2,
        b: 4,
        c: {
          c1: 1,
        },
        dd: [2],
      };

      observer(data);
      // data.dd.push(111);
    //   data.dd.pop();

      function defineReactive(target, key, value) {
        observer(value); // 深度监听
        Object.defineProperty(target, key, {
          get() {
            return value;
          },
          set(newVal) {
            if (newVal !== value) {
              observer(newVal); // 新值如果是对象，也要进行深度监听
              value = newVal;
              render();
            }
          },
        });
      }

      function observer(target) {
        if (typeof target !== "object" || target === null) {
          return target;
        }

        if (Array.isArray(target)) {
          target.__proto__ = newObj;
        }

        for (let key in target) {
          defineReactive(target, key, target[key]);
        }
      }

      function render() {
        console.log("假装是DOM");
      }




    </script>
  </body>
</html>
